/**
 * 主动报工页面JS
 */

$(document).ready(function() {
    // 订单选择变化事件
    $('#order-select').on('change', function() {
        var orderId = $(this).val();
        if (orderId) {
            loadOrderModels(orderId);
        } else {
            $('#order-model-select').html('<option value="">请先选择订单</option>');
            $('#order-info').hide();
        }
    });
    
    // 产品型号和工序选择变化事件
    $('#order-model-select').on('change', function() {
        var selectedValue = $(this).val();
        if (selectedValue) {
            var selectedOption = $(this).find('option:selected');
            var piecePrice = parseFloat(selectedOption.data('piece-price'));
            var timePrice = parseFloat(selectedOption.data('time-price'));
            var orderQuantity = parseInt(selectedOption.data('order-quantity'));
            
            // 显示价格信息
            $('#piece-price').text(piecePrice.toFixed(2));
            $('#time-price').text(timePrice.toFixed(2));
            $('#price-info').show();
            
            // 更新最大可报工数量（使用订单数量作为参考）
            $('#max-quantity').text(orderQuantity);
            $('#quantity-input').attr('max', orderQuantity);
            
            // 显示订单信息
            $('#total-quantity').text(orderQuantity);
            $('#allocated-quantity').text('0');
            $('#available-quantity').text(orderQuantity);
            $('#order-info').show();
        } else {
            $('#price-info').hide();
            $('#order-info').hide();
        }
    });
    
    // 报工类型切换
    $('input[name="report_type"]').on('change', function() {
        var type = $(this).val();
        if (type === 'piece') {
            $('#piece-section').show();
            $('#time-section').hide();
            $('#time-range-section').hide();
        } else {
            $('#piece-section').hide();
            $('#time-section').show();
            $('#time-range-section').show();
        }
    });
    
    // 时间计算
    $('#start-time, #end-time').on('change', function() {
        calculateWorkHours();
    });
    
    // 表单提交
    $('#activeReportForm').on('submit', function(e) {
        e.preventDefault();
        submitActiveReport();
    });
});

// 加载订单的产品型号和工序
function loadOrderModels(orderId) {
    $.ajax({
        url: '/index/worker/getOrderModels',
        method: 'GET',
        data: { order_id: orderId },
        success: function(response) {
            if (response.code === 1) {
                var options = '<option value="">请选择产品型号和工序</option>';
                response.data.forEach(function(item) {
                    var displayText = item.display_name + ' - 订单数量:' + item.order_quantity;
                    options += '<option value="' + item.model_id + ':' + item.process_id + '" ' +
                              'data-piece-price="' + item.piece_price + '" ' +
                              'data-time-price="' + item.time_price + '" ' +
                              'data-order-quantity="' + item.order_quantity + '">' + displayText + '</option>';
                });
                $('#order-model-select').html(options);
            } else {
                alert(response.msg || '加载产品型号失败');
            }
        },
        error: function() {
            alert('网络错误，请重试');
        }
    });
}

// 计算工作时长
function calculateWorkHours() {
    var startTime = $('#start-time').val();
    var endTime = $('#end-time').val();
    
    if (startTime && endTime) {
        var start = new Date('2000-01-01 ' + startTime);
        var end = new Date('2000-01-01 ' + endTime);
        
        if (end > start) {
            var diffHours = (end - start) / (1000 * 60 * 60);
            $('#calculated-hours').text(diffHours.toFixed(2));
            $('#work-hours-input').val(diffHours.toFixed(2));
            $('#time-calculator').show();
        } else {
            $('#time-calculator').hide();
            alert('结束时间必须晚于开始时间');
        }
    } else {
        $('#time-calculator').hide();
    }
}

// 提交主动报工
function submitActiveReport() {
    var formData = new FormData($('#activeReportForm')[0]);
    var btn = $('#activeReportForm button[type=submit]');
    var originalText = btn.html();
    
    btn.html('<i class="fa fa-spinner fa-spin"></i> 提交中...').prop('disabled', true);
    
    $.ajax({
        url: window.location.href,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.code === 1) {
                alert('报工提交成功！');
                setTimeout(function() {
                    window.location.href = '/index/worker/index';
                }, 1500);
            } else {
                alert(response.msg || '提交失败');
                btn.html(originalText).prop('disabled', false);
            }
        },
        error: function() {
            alert('网络错误，请重试');
            btn.html(originalText).prop('disabled', false);
        }
    });
} 